import reportService from "@/api/services/tool/reportService";
import TableDictTag from "@/components/grid/TableDictTag";
import useDictionaryBatch from "@/hooks/system/useDictionaryBatch";
import type { CustomReportField } from "@/pages/tool/customReport/entity";
import { Button, Card, Form, Input, Select, Table } from "antd";
import type { TableRowSelection } from "antd/es/table/interface";
import type { FC } from "react";
import { useEffect, useMemo, useState } from "react";

export enum SelectionType {
	DEFAULT = "default",
	CHECKBOX = "checkbox",
	RADIO = "radio",
}

interface DynamicQueryTableProps {
	/**
	 * 报表编码
	 */
	reportCode: string;
	/**
	 * sql参数
	 */
	params?: any;
	/**
	 * 选择类型, 默认不显示, 可选值: default, checkbox, radio
	 * @default DEFAULT
	 * checkbox 多选，radio 单选
	 */
	selectionType?: SelectionType;
	onSelectChange?: (selectedRows: any[]) => void;
}

const DynamicQueryTable: FC<DynamicQueryTableProps> = ({
	reportCode,
	params,
	selectionType = SelectionType.DEFAULT,
	onSelectChange,
}) => {
	const [form] = Form.useForm();
	const [searchFields, setSearchFields] = useState<CustomReportField[]>([]);
	const [columnFields, setColumnFields] = useState<any[]>([]);
	const [data, setData] = useState<any[]>([]);
	const [loading, setLoading] = useState(false);
	const [pagination, setPagination] = useState({ current: 1, pageSize: 10, total: 0 });

	// 所有字段中涉及到的 dictCode，批量加载避免组件内用 hook 判断
	const dictCodes = useMemo(() => searchFields.filter((f) => f.dictCode).map((f) => f.dictCode!), [searchFields]);
	const dictMap = useDictionaryBatch(dictCodes);

	const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
	const [selectedRows, setSelectedRows] = useState<any[]>([]);

	useEffect(() => {
		initTable();
		fetchData();
	}, [reportCode]);

	const initTable = async () => {
		const res = await reportService.getFieldsByCode(reportCode);
		const search = res.filter((f) => f.isQuery === 1);
		setSearchFields(search);

		const columns = res
			.filter((f) => f.isVisible === 1)
			.map((f) => ({
				title: f.fieldComment || f.fieldName,
				dataIndex: f.fieldName,
				key: f.fieldName,
				render: (value: any) => (f.dictCode ? <TableDictTag dictCode={f.dictCode} value={value} /> : value),
			}));
		setColumnFields(columns);
	};

	const fetchData = async () => {
		setLoading(true);
		const queryParams = form.getFieldsValue();
		const res = await reportService.getReportData({
			reportCode,
			params: { ...queryParams, ...params },
			page: pagination.current,
			pageSize: pagination.pageSize,
		});
		setData(res.records);
		setPagination((prev) => ({ ...prev, total: res.total }));
		setLoading(false);
	};

	const handleSearch = () => {
		setPagination({ ...pagination, current: 1 });
		fetchData();
	};

	const handleTableChange = (paginationInfo: any) => {
		setPagination(paginationInfo);
		fetchData();
	};

	const rowSelection: TableRowSelection<any> | undefined =
		selectionType === SelectionType.DEFAULT
			? undefined
			: {
					type: selectionType === SelectionType.CHECKBOX ? "checkbox" : "radio",
					selectedRowKeys,
					onChange: (keys: React.Key[], rows: any[]) => {
						setSelectedRowKeys(keys);
						setSelectedRows(rows);
						onSelectChange?.(rows);
					},
				};

	return (
		<>
			{searchFields.length > 0 && (
				<Card className="mb-4">
					<Form form={form} layout="inline">
						{searchFields.map((field) => (
							<Form.Item name={field.fieldName} label={field.fieldComment || field.fieldName} key={field.fieldName}>
								{field.dictCode ? (
									<Select allowClear style={{ width: 160 }} options={dictMap[field.dictCode] || []} />
								) : (
									<Input allowClear style={{ width: 160 }} />
								)}
							</Form.Item>
						))}
						<Form.Item>
							<Button type="primary" onClick={handleSearch}>
								查询
							</Button>
							<Button
								className="ml-2"
								onClick={() => {
									form.resetFields();
									handleSearch();
								}}
							>
								重置
							</Button>
						</Form.Item>
					</Form>
				</Card>
			)}
			<div className="h-4" />
			<Table
				rowKey="id"
				loading={loading}
				columns={columnFields}
				dataSource={data}
				pagination={pagination}
				onChange={handleTableChange}
				rowSelection={rowSelection}
				scroll={{
					y: "calc(100vh - 510px)", // 动态高度（根据 Modal 剩余空间调整）
					x: "max-content", // 按内容自适应宽度
				}}
				sticky={{
					offsetHeader: 0, // 表头固定
				}}
				onRow={
					selectionType !== SelectionType.DEFAULT
						? (record) => ({
								onClick: () => {
									const key = record.id;
									let newSelectedRowKeys: React.Key[];
									let newSelectedRows: any[];

									if (selectionType === SelectionType.RADIO) {
										// 单选模式 - 如果点击已选中的行，不做任何操作（不允许取消选择）
										if (selectedRowKeys.includes(key)) {
											// 如果已选中，则取消选中
											newSelectedRowKeys = [];
											newSelectedRows = [];
										} else {
											// 否则选中当前行
											newSelectedRowKeys = [key];
											newSelectedRows = [record];
										}
									} else {
										// 多选模式
										if (selectedRowKeys.includes(key)) {
											// 如果已选中，则取消选中
											newSelectedRowKeys = selectedRowKeys.filter((k) => k !== key);
											newSelectedRows = selectedRows.filter((r) => r.id !== key);
										} else {
											// 如果未选中，则添加选中
											newSelectedRowKeys = [...selectedRowKeys, key];
											newSelectedRows = [...selectedRows, record];
										}
									}

									setSelectedRowKeys(newSelectedRowKeys);
									setSelectedRows(newSelectedRows);
									onSelectChange?.(newSelectedRows);
								},
							})
						: undefined
				}
			/>
		</>
	);
};

export default DynamicQueryTable;
